package com.vitabuybuy.tv.ui.cart

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.library.common.base.BaseFragment
import com.library.common.base.MessageModel
import com.library.common.dto.MessageEvent
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.FragmentCartBinding
import com.vitabuybuy.tv.ui.cart.adapter.ShopMallAdapter
import com.vitabuybuy.tv.ui.cart.viewmodel.CartViewModel
import com.vitabuybuy.tv.ui.shopcenter.adapter.RecommendCommodityListAdapter
import com.vitabuybuy.tv.utils.EventCode
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.dialog.StoreCouponsPopup
import com.library.common.toast.XToast
import com.library.common.util.DensityUtil
import com.library.common.widget.RecycleViewDivider
import com.vitabuybuy.tv.ui.shopcenter.GoodsDetailsActivity
import kotlinx.android.synthetic.main.fragment_cart.*
import kotlinx.android.synthetic.main.fragment_cart.rcvRecommendCommodity
import kotlinx.android.synthetic.main.fragment_cart.refresh

/**
 * 作者：SimGa
 * 日期：2020/11/29
 * 时间：10:49
 * 包名：com.vitabuybuy.tv.ui.cart
 */

class CartFragment : BaseFragment<CartViewModel, FragmentCartBinding>() {
    override val layoutId: Int
        get() = R.layout.fragment_cart

    private val shopMallAdapter by lazy { ShopMallAdapter() }
    private val recommendAdapter by lazy { RecommendCommodityListAdapter() }
    private var pageNumber = 1
    private var couponsPopup: StoreCouponsPopup? = null
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.run {
            totalAmount = 0.00
            isClickAll = false
            mViewModel = viewModel
        }
        rcvCart.apply {
            adapter = shopMallAdapter
            layoutManager = LinearLayoutManager(mContext)
            addItemDecoration(RecycleViewDivider(mContext, 10))
            isNestedScrollingEnabled = false
        }
        rcvRecommendCommodity.apply {
            adapter = recommendAdapter
            layoutManager = GridLayoutManager(context, 2)
            isNestedScrollingEnabled = false
        }
    }

    override fun lazyLoadData() {
        if (mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
            viewModel.getCartGoodsDetails()
            viewModel.cartGoodslist.observe(this, Observer {
                shopMallAdapter.setNewData(it)
                val lp = status_view.layoutParams as ViewGroup.MarginLayoutParams
                when (shopMallAdapter.mData.size) {
                    0 -> {
                        tvEdit.visibility = View.INVISIBLE
                        lp.height = DensityUtil.dip2px(315f)
                        status_view.showEmpty()
                    }
                    else -> {
                        tvEdit.visibility = View.VISIBLE
                        lp.height = ViewGroup.MarginLayoutParams.WRAP_CONTENT
                        status_view.showContent()
                    }
                }
                status_view.layoutParams = lp
                calculateAllAmount()
            })
        }
        viewModel.getGoodsList(-1, "featured", pageNumber)
    }

    override fun observeData() {
        viewModel.goodlist.observe(this, Observer {
            refresh.onLoad(it.size)
            if (pageNumber == 1) {
                recommendAdapter.setNewData(it)
            } else {
                recommendAdapter.addData(it)
            }
        })
        viewModel.couponsList.observe(this, Observer {
            if (it.size == 0) {
                XToast.normal(getString(R.string.this_store_has_no_coupons))
                return@Observer
            }
            couponsPopup = StoreCouponsPopup(
                mContext,
                it,
                StoreCouponsPopup.RECEIVER_COUPONS
            ) { it, position ->
                viewModel.saveACoupon(it.id, position)
            }
            couponsPopup!!.showPopupWindow()
        })
    }

    override fun eventHandling() {
        setOnclickNoRepeat(tvEdit, btnSettleAccounts, ivChoose, tvAll){v->
            when (v) {
                tvEdit -> {
                    if (tvTotalPrice.visibility == View.VISIBLE) {
                        tvEdit.text = getString(R.string.finish)
                        btnSettleAccounts.text = getString(R.string.delete)
                        tvTotalPrice.visibility = View.GONE
//                    btnMoveToCollection.visibility = View.VISIBLE
                    } else {
                        tvEdit.text = getString(R.string.edit)
                        btnSettleAccounts.text = getString(R.string.settle_accounts)
                        tvTotalPrice.visibility = View.VISIBLE
//                    btnMoveToCollection.visibility = View.GONE
                    }
                }
                btnSettleAccounts -> {
                    if (getCheckItemId().size <= 0) return@setOnclickNoRepeat
                    when (btnSettleAccounts.text) {
                        getString(R.string.settle_accounts) -> {
                            ConfirmOrderActivity.openActivity(
                                mContext,
                                getCheckItemId(),
                                ConfirmOrderActivity.SETTLEMENT_ORDER
                            )
                        }
                        getString(R.string.delete) -> {
                            AlertDialog.Builder(mContext)
                                .setTitle(getString(R.string.logout))
                                .setMessage(getString(R.string.are_you_sure_delete_cart))
                                .setCancelable(true)
                                .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                                    viewModel.deleteCart(getCheckItemId())
                                }
                                .setNegativeButton(getString(R.string.cancel)) { _, _ -> }.create()
                                .show()
                        }
                    }
                }
                ivChoose, tvAll -> {
                    mBinding.isClickAll = !mBinding.isClickAll!!
                    for (item in shopMallAdapter.mData) {
                        item.isChecked = mBinding.isClickAll!!
                        for (good in item.itemList) {
                            good.isChecked = mBinding.isClickAll!!
                        }
                    }
                    shopMallAdapter.notifyDataSetChanged()
                    calculateAllAmount()
                }
            }
        }
        shopMallAdapter.onAddClick = { cartId, itemPosition, parentPosition ->
            viewModel.addCartQulitity(cartId, itemPosition, parentPosition)
        }
        shopMallAdapter.onReductClick = { cartId, itemPosition, parentPosition ->
            viewModel.reduceCartQulitity(cartId, itemPosition, parentPosition)
        }
        shopMallAdapter.onClickParentChoose = {
            calculateAllAmount()
        }
        shopMallAdapter.onClickCoupons = {
            viewModel.getStoreCouponsList(shopMallAdapter.mData[it].id)
        }
        refresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber++
                viewModel.getGoodsList(-1, "featured", pageNumber)
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                viewModel.getCartGoodsDetails()
                pageNumber = 1
                viewModel.getGoodsList(-1, "featured", pageNumber)
            }
        })
        recommendAdapter.setOnItemClickListener { _, item, _ ->
            GoodsDetailsActivity.openActivity(mContext, item.id)
        }
    }

    //计算选中金额
    private fun calculateAllAmount() {
        var amount = 0.00
        var clickNum = 0
        for (item in shopMallAdapter.mData) {
            if (item.isChecked) {
                clickNum++
            }
            for (good in item.itemList) {
                if (good.isChecked) {
                    amount += good.amount
                }
            }
        }
        mBinding.isClickAll =
            (clickNum == shopMallAdapter.mData.size && shopMallAdapter.mData.size != 0)
        mBinding.totalAmount = amount
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1, 2 -> {
                shopMallAdapter.mData[msg.arg2].itemList[msg.arg1].quantity =
                    if (msg.code == 1) {
                        shopMallAdapter.mData[msg.arg2].itemList[msg.arg1].quantity + 1
                    } else {
                        shopMallAdapter.mData[msg.arg2].itemList[msg.arg1].quantity - 1
                    }
                shopMallAdapter.mData[msg.arg2].itemList[msg.arg1].amount =
                    shopMallAdapter.mData[msg.arg2].itemList[msg.arg1].quantity * shopMallAdapter.mData[msg.arg2].itemList[msg.arg1].price
                shopMallAdapter.notifyItemChanged(msg.arg2)
                calculateAllAmount()
            }
            3 -> {
                //删除完成后，重新获取购物车
                viewModel.getCartGoodsDetails()
                mBinding?.run {
                    totalAmount = 0.00
                    isClickAll = false
                }
            }
            4 -> {
                XToast.success(getString(R.string.already_save_coupon))
                couponsPopup?.run {
                    this.couponsAdapter.mData[msg.arg1].isReceived = true
                    this.couponsAdapter.notifyItemChanged(msg.arg1)
                }
            }
        }
    }

    private fun getCheckItemId(): ArrayList<Int> {
        val idList = ArrayList<Int>()
        for (item in shopMallAdapter.mData) {
            for (good in item.itemList) {
                if (good.isChecked) {
                    idList.add(good.id)
                }
            }
        }
        return idList
    }

    override fun onEvent(event: MessageEvent) {
        when (event.code) {
            EventCode.updae_cart -> {
                viewModel.getCartGoodsDetails()
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            if (mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                viewModel.getCartGoodsDetails()
            } else {
                tvEdit.visibility = View.INVISIBLE
                viewModel.cartGoodslist.value!!.clear()
                val lp = status_view.layoutParams as ViewGroup.MarginLayoutParams
                lp.height = DensityUtil.dip2px(315f)
                status_view.showEmpty()
            }
        }
    }
}